using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace GetSharePointToValidate.Deployment
{
    public class ModifierCompatBrower
    {
        SPWebApplication webApplication;
        public ModifierCompatBrower(SPWebApplication WebApplication)
        {
            webApplication = WebApplication;
        }
        public void Modifier(bool AddModifierOrRemoveModifier)
        {
            Hashtable ControlAdapterCollection = new Hashtable();
            ControlAdapterCollection.Add("Microsoft.SharePoint.Publishing.PublishingLayoutPage, Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c", "GetSharePointToValidate.Adapters.GSPTV_PageAdapter, GetSharePointToValidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3e3ec44179df1db8");
            ControlAdapterCollection.Add("System.Web.UI.WebControls.WebParts.WebPartZone, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "GetSharePointToValidate.Adapters.GSPTV_WebPartZone, GetSharePointToValidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3e3ec44179df1db8");
            ControlAdapterCollection.Add("Microsoft.SharePoint.Publishing.WebControls.RichHtmlField, Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c", "GetSharePointToValidate.Adapters.GSPTV_RichHtmlField, GetSharePointToValidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3e3ec44179df1db8");
            ControlAdapterCollection.Add("Microsoft.SharePoint.Publishing.WebControls.RichImageField, Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c", "GetSharePointToValidate.Adapters.GSPTV_RichImageField, GetSharePointToValidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3e3ec44179df1db8");
            ControlAdapterCollection.Add("Microsoft.SharePoint.Publishing.WebControls.SummaryLinkFieldControl, Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c", "GetSharePointToValidate.Adapters.GSPTV_SummaryLinkFieldControl, GetSharePointToValidate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3e3ec44179df1db8");

            string pathPost = @"\App_Browsers\compat.browser";
            string fullPath = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                foreach (KeyValuePair<SPUrlZone, SPIisSettings> kvp in webApplication.IisSettings)
                {
                    SPIisSettings iisSetting = kvp.Value as SPIisSettings;
                    string pathPast = iisSetting.Path.FullName;
                    XmlDocument document = new XmlDocument();
                    fullPath = string.Concat(pathPast, pathPost);
                    document.Load(fullPath);

                    //Add BrowerElemnt to the document
                    EnsureBrowerElement(document);

                    //Add controlAdaptersElement
                    EnsureControlAdaptersElement(document);

                    if (AddModifierOrRemoveModifier)
                    {
                        //Add ControlAdapterElements
                        EnsureControlAdapterElementCollection(document, ControlAdapterCollection);
                    }
                    if (!AddModifierOrRemoveModifier)
                    {
                        //Remove ControlAdapterElements
                        RemoveControlAdapterElementCollection(document, ControlAdapterCollection);
                    }

                    document.Save(fullPath);
                }
            });
        }

        /// <summary>
        /// Ensure that the <browser refID="Default"> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <returns>The new element node that has been added</returns>
        public XmlNode EnsureBrowerElement(XmlDocument Document)
        {
            XmlNode nodeBrowers;
            if (IsBrowserElementAdd(Document))
            {
                nodeBrowers = Document.SelectSingleNode("browsers/browser[@refID='Default']");
            }
            else
            {
                nodeBrowers = Document.CreateNode(XmlNodeType.Element, "browser", "");
                XmlAttribute attributeRefID = Document.CreateAttribute("refID");
                attributeRefID.Value = "Default";
                nodeBrowers.Attributes.Append(attributeRefID);
                Document.FirstChild.AppendChild(nodeBrowers);
            }
            return nodeBrowers;
        }

        /// <summary>
        /// Ensure that the <controlAdapters> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <returns>The new element node that has been added</returns>
        public XmlNode EnsureControlAdaptersElement(XmlDocument Document)
        {
            XmlNode nodeControlAdapters;


            //Call the BrowerElement metode to ensure that the <browser refID="Default"> is in the document
            XmlNode parentNode = EnsureBrowerElement(Document);

            if (IsControlAdaptersElementAdd(Document))
            {
                nodeControlAdapters = Document.SelectNodes("browsers/browser[@refID='Default']/controlAdapters").Item(0);
            }
            else
            {
                nodeControlAdapters = Document.CreateNode(XmlNodeType.Element, "controlAdapters", "");
                parentNode.AppendChild(nodeControlAdapters);
            }
            return nodeControlAdapters;
        }

        /// <summary>
        /// Ensure that the <adapter controlType="hash key" adapterType="hash value" /> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <returns>The new element node that has been added</returns>
        public void EnsureControlAdapterElementCollection(XmlDocument Document, Hashtable AdapterCollection)
        {
            //Call the BrowerElement metode to ensure that the <controlAdapters> is in the document
            XmlNode parentNode = EnsureControlAdaptersElement(Document);

            foreach (DictionaryEntry Entry in AdapterCollection)
            {
                if (Document.SelectNodes(string.Format("browsers/browser[@refID='Default']/controlAdapters/adapter[@controlType='{0}']", Entry.Key)).Count.Equals(0))
                {
                    XmlNode node = Document.CreateNode(XmlNodeType.Element, "adapter", "");
                    XmlAttribute controlType = Document.CreateAttribute("controlType");
                    controlType.Value = Entry.Key.ToString();
                    node.Attributes.Append(controlType);

                    XmlAttribute adapterType = Document.CreateAttribute("adapterType");
                    adapterType.Value = Entry.Value.ToString();
                    node.Attributes.Append(adapterType);

                    parentNode.AppendChild(node);
                }
            }
        }

        /// <summary>
        /// Remove the <adapter controlType="hash key" adapterType="hash value" /> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <param name="AdapterCollection"></param>
        public void RemoveControlAdapterElementCollection(XmlDocument Document, Hashtable AdapterCollection)
        {
            //Call the BrowerElement metode to ensure that the <controlAdapters> is in the document
            XmlNode parentNode = EnsureControlAdaptersElement(Document);

            foreach (DictionaryEntry Entry in AdapterCollection)
            {
                XmlNodeList nodeList = Document.SelectNodes(string.Format("browsers/browser[@refID='Default']/controlAdapters/adapter[@controlType='{0}']", Entry.Key));
                if (nodeList.Count.Equals(1))
                {
                    XmlNode node = nodeList.Item(0);
                    parentNode.RemoveChild(node);
                }
            }
        }

        /// <summary>
        /// Test if the <browser refID="Default"> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <returns>true if there are a <browser refID="Default"> in the document</returns>
        public bool IsBrowserElementAdd(XmlDocument Document)
        {
            XmlNodeList nodeList = Document.SelectNodes("browsers/browser[@refID='Default']");
            return !nodeList.Count.Equals(0);
        }
        /// <summary>
        /// Test if the <controlAdapters> is in the document
        /// </summary>
        /// <param name="Document"></param>
        /// <returns>true if there are a <browser refID="Default"> in the document</returns>
        public bool IsControlAdaptersElementAdd(XmlDocument Document)
        {
            XmlNodeList nodeList = Document.SelectNodes("browsers/browser[@refID='Default']/controlAdapters");
            return !nodeList.Count.Equals(0);
        }

    }
}
